/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
#include <stdlib.h>
#include <string.h>
#include <types.h>
#include <Signal.h>
#include <time.h>

 static uint64_t uptimeMillis() {
     struct timespec now;
     clock_gettime(CLOCK_MONOTONIC, &now);
     uint64_t ns = (((uint64_t) now.tv_sec * 1000000000LL) + now.tv_nsec);
     return ns / 1000000;
 }

 SignalType* newSignal() {
    SignalType* sig = (SignalType*)malloc(sizeof(SignalType));
    if (!sig) {
        return NULL;
    }

    memset(sig, 0, sizeof(SignalType));

    sig->mLock = newLock();
    if (!sig->mLock) {
        free(sig);
        return NULL;
    }
    
    pthread_condattr_init(&sig->mCondAttr);
    pthread_condattr_setclock(&sig->mCondAttr, CLOCK_MONOTONIC);
    pthread_cond_init(&sig->mCond, &sig->mCondAttr);
    pthread_mutex_init(&sig->mLock->mutex, NULL);
    return sig;
}

 void deleteSignal(SignalType* sig) {
    if (sig) {
        if (sig->mLock) {
            deleteLock(sig->mLock);
        }
        pthread_cond_destroy(&sig->mCond);
        pthread_condattr_destroy(&sig->mCondAttr);
        free(sig);
    }
 }


void signalWait(SignalType* sig, uint32_t timeout) {
    uint64_t timeoutTimestamp = (uptimeMillis() + timeout) * 1000000LL;
    struct timespec timeSpec;

    if (!sig || !sig->mLock) {
        return;
    }
    
    timeSpec.tv_sec = timeoutTimestamp / 1000000000LL;
    timeSpec.tv_nsec = timeoutTimestamp % 1000000000LL;
    pthread_mutex_lock(&sig->mLock->mutex);
    pthread_cond_timedwait(&sig->mCond, &sig->mLock->mutex, &timeSpec);
    pthread_mutex_unlock(&sig->mLock->mutex);
}
void setSignal(SignalType* sig) {
    if (!sig || !sig->mLock) {
        return;
    }

    pthread_mutex_lock(&sig->mLock->mutex);
    pthread_cond_signal(&sig->mCond);
    pthread_mutex_unlock(&sig->mLock->mutex);
}

